<?php
/**
 * Created by PhpStorm.
 * User: MADAO
 * Date: 2019/9/28
 * Time: 11:37
 */

namespace App\Services;

use App\Model\Article;
use Hyperf\Database\Model\Collection;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Elasticsearch\ClientBuilderFactory;

class EsService
{
    protected $client;


    const TYPE = '_doc';

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $builder = $container->get(ClientBuilderFactory::class)->create();
        $this->client = $builder->setHosts(['http://127.0.0.1:9200'])->build();
    }

    public function update(Collection $models)
    {
        $params['body'] = [];

        $models->each(function (Article $model) use (&$params) {
            $params['body'][] = [
                'update' => [
                    '_id' => $model->getKey(),
                    '_index' => 'blog_test_2',
                ]
            ];
            $params['body'][] = [
                'doc' => [
                    'title' => $model->title ?? '',
                    'content' => $model->content ?? '',
                ],
                'doc_as_upsert' => true
            ];
        });

        $this->client->bulk($params);
    }

    public function delete(Collection $models)
    {
        $params['body'] = [];
        $models->each(function (Article $model) use (&$params) {
            $params['body'] = [
                'delete' => [
                    '_id' => $model->getKey(),
                    '_index' => 'blog_test_2',
                    '_type' => self::TYPE,
                ]
            ];
        });
        $this->client->bulk($params);
    }

    public function search()
    {

    }

    public function paginate()
    {

    }

    public function mapIds()
    {

    }

    public function map()
    {

    }

    public function getTotalCount()
    {

    }

    public function flush()
    {

    }

    public function createDoc()
    {
        $this->client->create([
        ]);
    }

    public function updateDoc()
    {
        $this->client->update([

        ]);
    }
}
